package iec104;

public class IEC104 extends ASDU {
	private int apdulen = 0;

	IEC104(int rtu) {
		super(rtu);
	}

	private int Send(short[] data, int len) {
		System.out.printf("len :%d\n",len);
		for (int index = 0; index < len; index++) {
			System.out.printf(" %02x ", data[index]);
		}
		return len;
	}

	int getApdulen() {
		return apdulen;
	}

	private int SendApdu(int typeid, int reason,short[] data, int len,int num,boolean sq) {
		short[] apdu = new short[512];
		int offset = 0;
		int lenflag = 0;
		apdu[offset++] = 0x68;
		apdu[lenflag = offset++] = 0;
		apdu[offset++] = 02;
		apdu[offset++] = 00;
		apdu[offset++] = 02;
		apdu[offset++] = 00;
		System.out.printf("\ns:%d ", num);
		VSQ vsq = new VSQ();
		if(sq)
			vsq.setVSQ(num, 1);
		else
			vsq.setVSQ(num, 0);
		vsq.getVSQ();
		System.out.printf("\ns1:%d ", vsq.getVSQ());
		REASON rea = new REASON();
		rea.setReason(reason, 0, 0, 0);
		short[] asdu1 = PackageAsdu(typeid, vsq.getVSQ(), rea.getReason(), data, len);
		System.arraycopy(asdu1, 0, apdu, offset, getAsdulen());
		offset += getAsdulen();
		apdu[lenflag] = (short) (offset - 2);
		apdulen = offset;
		return Send(apdu, offset);
	}

	int Send_100_C_IC_NA_1(int reason)
	{
		int infoaddr=0;
		short[] body=new short[4];
		body[3]=0x14;
		body[0]=(short) (infoaddr&0xFF);
		body[1]=(short) ((infoaddr>>8)&0xFF);
		body[2]=(short) ((infoaddr>>16)&0xFF);
		return SendApdu(ASDU.C_IC_NA_1,reason,body,4,1,false);
	}
	int Send_1_M_SP_NA_1_GI()
	{
		short[] body=new short[243];
		int firstinfoaddr=0x001;
		int len=0;
		short[] addrbody=new short[3];
		addrbody[0]=(short) (firstinfoaddr&0xFF);
		addrbody[1]=(short) ((firstinfoaddr>>8)&0xFF);
		addrbody[2]=(short) ((firstinfoaddr>>16)&0xFF);
		len+=3;
		System.arraycopy(addrbody, 0, body, 0, len);
		int ii=0;
		for(ii=0;ii<200;ii++)
		{
			SIQ siq=new SIQ();
			body[len]=(short) (siq.setSIQ(0, false, false, false, false)&0xFF);
			len+=1;
			if((len+1)>243)
			{
				break;
			}
			if(ii>=127)
			{
				break;
			}
		}
		System.out.printf("\nsfdadf:%d ", ii);
		return SendApdu(ASDU.M_SP_NA_1,REASON.COT_INTERROGATED_BY_STATION,body,len,ii,true);
	}
}
